package com.polukeuro.app.client.manager;

import com.polukeuro.app.client.events.ConsummerLoadDataEvent;
import com.polukeuro.app.client.events.ConsummerLoadErrorDataEvent;
import com.polukeuro.app.client.events.ProviderHandler;
import com.polukeuro.app.client.events.ProviderNeedDataEvent;
import com.polukeuro.app.client.events.ProviderSetDataEvent;
import com.polukeuro.app.client.events.ProviderSetErrorDataEvent;
import com.polukeuro.app.client.events.RequestEvent;
import com.polukeuro.app.client.events.RequestHandler;
import com.polukeuro.app.client.events.ResponseErrorEvent;
import com.polukeuro.app.client.events.ResponseEvent;
import com.polukeuro.app.share.request.GenericRequestCallback;
import com.polukeuro.app.share.request.RequestHelper;

public final class DataManager implements RequestHandler, ProviderHandler{
	
	private static DataManager DM = null;
	
	//singleton
	private DataManager() {
		EventManager.getHandler().addHandler(ProviderNeedDataEvent.getType(), this);
		EventManager.getHandler().addHandler(ProviderSetDataEvent.getType(), this);
		EventManager.getHandler().addHandler(ProviderSetErrorDataEvent.getType(), this);
		EventManager.getHandler().addHandler(RequestEvent.getType(), this);
		EventManager.getHandler().addHandler(ResponseErrorEvent.getType(), this);
		EventManager.getHandler().addHandler(ResponseEvent.getType(), this);
	}
	
	public static DataManager getInstance() {
		if(DM == null) {
			DM =  new DataManager();
		}
		return DM;
	}
	
	public void needData(ProviderNeedDataEvent event) {
		EventManager.getHandler().fireEvent(new RequestEvent(event.getUrl()));
	}
	
	public void setData(ProviderSetDataEvent event) {
		EventManager.getHandler().fireEvent(new ConsummerLoadDataEvent(event.getJson()));
	}

	public void setErrorData(ProviderSetErrorDataEvent event) {
		EventManager.getHandler().fireEvent(new ConsummerLoadErrorDataEvent(event.getException().getMessage()));
	}

	public void onRequestEvent(RequestEvent event) {
		RequestHelper.doGet(event.getUrl(), new GenericRequestCallback());
	}

	public void onResponseErrorEvent(ResponseErrorEvent event) {
		EventManager.getHandler().fireEvent(new ProviderSetErrorDataEvent(event.getException()));
	}

	public void onResponseEvent(ResponseEvent event) {
		EventManager.getHandler().fireEvent(new ProviderSetDataEvent(event.getJson()));
	}

}
